package com.vegetable.modules.controller.wx;

import com.alibaba.fastjson.JSONObject;
import com.vegetable.common.annotation.SysLog;
import com.vegetable.common.utils.R;
import com.vegetable.modules.controller.AbstractController;
import com.vegetable.modules.entity.wx.WxDepartment;
import com.vegetable.modules.service.wx.WxCpDepartmentSyncService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 企业微信部门同步控制器
 * 提供同步企业微信通讯录部门结构的API接口
 *
 * @author Qoder
 */
@Slf4j
@RestController
@RequestMapping("/wx/department")
@AllArgsConstructor
@Api(value = "企业微信部门同步", tags = "企业微信部门同步")
public class WxCpDepartmentSyncController extends AbstractController {

    private final WxCpDepartmentSyncService wxCpDepartmentSyncService;

    /**
     * 同步企业微信部门结构
     */
    @SysLog(value = "同步企业微信部门结构")
    @PostMapping("/sync")
    @ApiOperation(value = "同步企业微信部门结构", notes = "从企业微信拉取通讯录部门结构")
    public R<Boolean> syncDepartmentStructure() {
        try {
            log.info("开始同步企业微信部门结构");
            
            wxCpDepartmentSyncService.syncDepartmentStructure();
            
            log.info("企业微信部门结构同步完成");
            return R.data(true, "同步完成");
        } catch (Exception e) {
            log.error("同步企业微信部门结构失败", e);
            return R.fail("同步失败: " + e.getMessage());
        }
    }
    
    /**
     * 从数据库获取所有部门信息（不实时从企业微信获取）
     */
    @SysLog(value = "获取本地部门信息")
    @GetMapping("/list/local")
    @ApiOperation(value = "获取本地部门信息", notes = "从数据库获取所有部门信息，不实时从企业微信获取")
    public R<List<WxDepartment>> getLocalDepartments() {
        try {
            log.info("开始从数据库获取所有部门信息");
            
            List<WxDepartment> departments = wxCpDepartmentSyncService.getLocalDepartments();
            
            log.info("从数据库获取部门信息完成，共 {} 个部门", departments.size());
            return R.data(departments, "获取成功");
        } catch (Exception e) {
            log.error("从数据库获取部门信息失败", e);
            return R.fail("获取失败: " + e.getMessage());
        }
    }
}